package com.tian.controller;

import com.alibaba.fastjson.JSON;
import com.tian.entity.ChargeUser;
import com.tian.mapper.ChargeUserMapper;
import com.tian.util.RedisConstantPre;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-03-24 10:17
 * {@code @version:} 1.0
 */
@Slf4j
@Scope("prototype")
@RestController
public class TestController {
    @Resource
    RabbitTemplate userPointConfirmRabbitTemplate;
    @Resource
    ChargeUserMapper chargeUserMapper;
    @Resource
    private RedissonClient redissonClient;

    @GetMapping("/")
    public Object test() {
        RLock lock = redissonClient.getLock(RedisConstantPre.USER_INFO_ID_PRE + "userPointMessage.getUserId()");
        lock.lock();
        try {
            log.info("获取到了分布式锁");
            return chargeUserMapper.selectByPrimaryKey(1L);
        } finally {
            log.info("释放分布式锁");
            lock.unlock();
        }
    }

    @GetMapping("/push")
    public String push() {
        for (int i = 1; i <= 5; i++) {
            //这个参数是用来做消息的唯一标识
            //发布消息时使用，存储在消息的headers中
            ChargeUser user = chargeUserMapper.selectByPrimaryKey(1L);


            // 关联的数据，可以用在消息投递失败的时候，作为一个线索，比如我把当前用户的id放进去，如果user消息投递失败
            // 我后面可以根据id再找到user，再次投递数据
            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString().concat("-") + i);
            if (i == 2) {
                //故意把交换机写错，演示 confirmCallback
                userPointConfirmRabbitTemplate.convertAndSend("TestDirectExchange_111", "TestDirectRouting",
                        JSON.toJSONString(user), correlationData);
            } else if (i == 3) {
                //故意把路由键写错，演示 returnCallback
                userPointConfirmRabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting_111",
                        JSON.toJSONString(user), correlationData);
            } else {
                //正常发送
                userPointConfirmRabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting",
                        JSON.toJSONString(user), correlationData);
            }
        }
        return "producer push ok";
    }
}
